package com.neuedu.mvc.filter;


import com.neuedu.mvc.MVCStringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {


    // String ignoreURI[] = {"/login" ,"/login.jsp" };
    // String ignoreExt[] = {".css" ,".js" ,".png" };

    String ignoreURIs[] ; //忽略的URI
    String ignoreExts[] ; //忽略的扩展名

    public LoginFilter( ) {
        System.out.println("LoginFilter.LoginFilter 构造");
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String ignoreURI = filterConfig.getInitParameter("ignoreURI");
        String ignoreExt  = filterConfig.getInitParameter("ignoreExt");

        ignoreURIs = ignoreURI.split(",");
        ignoreExts = ignoreExt.split(",");
    }

    /**
     * 判断当前的URI或者是扩展名 是否例外
     * @param uri
     * @return
     */
    private boolean ingoreURI(String uri) {
        String ext = MVCStringUtils.getExt(uri);
        for (String ignoreExt : ignoreExts) {
            if(ignoreExt.equals(ext)){
                return  true;
            }
        }

        for (String ignoreURI : ignoreURIs) {
            if(ignoreURI.equals(uri)){
                return true;
            }
        }


        return false;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //查看会话中是否存在登录状态

        System.out.println("LoginFilter.doFilter");

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();

        // request.getRequestURL()  //  http://127.0.0.1:8080/mvc/index.jsp
        String uri = request.getRequestURI();   //  /mvc/login.jsp    /login
        uri = uri.substring(uri.lastIndexOf("/"));  // /login.jsp   /login
        //判断是否需要验证（）
        if(ingoreURI(uri)){
            //例外的
            //chain 链式对象 ,放行请求
            chain.doFilter(req, resp);
        }else{
            String username = (String)session.getAttribute("username");
            if(MVCStringUtils.isNotEmpty(username)){
                //chain 链式对象 ,放行请求
                chain.doFilter(req, resp);
            }else{
                response.sendRedirect(request.getContextPath()+"/login.jsp");
            }
        }

    }



    @Override
    public void destroy( ) {
        System.out.println("LoginFilter.destroy");
    }


    public static void main(String[] args) {

        // String uri = request.getRequestURI() ;
        String uri = "/mvc/juery.js";
        uri = uri.substring(uri.lastIndexOf("/"));
        String ext = uri.substring(uri.lastIndexOf("."));

        System.out.println("uri = " + uri);
        System.out.println("ext = " + ext);


    }
}
